﻿using FirstFloor.ModernUI.Windows.Controls;
using FirstFloor.ModernUI.Windows.Navigation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;

namespace Atlanchim.Crm.Mui.Helpers
{
    public static class TopNavigationHelper
    {
        private static ModernFrame _mainFrame;
        public static ModernFrame MainFrame
        {
            get
            {
                if (_mainFrame == null)
                {
                    DependencyObject startItem = App.Current.MainWindow;

                    _mainFrame = VisualTreeHelperExt.FindVisualChildren<ModernFrame>(App.Current.MainWindow).FirstOrDefault();
                }

                return _mainFrame;
            }
        }

        /// <summary>
        /// Permet de faire un retour arrière sur la page principale 
        /// en ne conservant pas de trace de la page courante dans l'historique
        /// </summary>
        public static void NavigateBackTopFrame()
        {
            if (MainFrame != null)
            {
                Stack<Uri> historyStack = (Stack<Uri>)MainFrame
                                                        .GetType()
                                                        .GetField("history", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)
                                                        .GetValue(MainFrame);
                MainFrame.Source = historyStack.Pop();

                // On ne conserve pas la trace de l'Uri courante.
                historyStack.Pop();
            }
        }

        /// <summary>
        /// Permet de naviguer vers l'Uri choisie au niveau de la page principale
        /// </summary>
        /// <param name="newTopUri"></param>
        public static void NavigateTopFrame(Uri newTopUri)
        {
            if (MainFrame != null)
            {
                MainFrame.Source = newTopUri;
            }
        }

        public static void OnCanGoToPage(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = e.Parameter is String || e.Parameter is Uri;
        }

        public static void OnGoToPage(object target, ExecutedRoutedEventArgs e)
        {
            var newValue = e.Parameter as Uri;

            if (newValue == null)
            {
                var newValueStr = e.Parameter as string;
                if (newValueStr != null)
                {
                    newValue = new Uri(newValueStr, UriKind.RelativeOrAbsolute);
                }
                else
                {
                    // no valid command parameter (not a uri or string), ignore
                    return;
                }
            }
            TopNavigationHelper.NavigateTopFrame(newValue);
        }


    }
}
